<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\energy;

use app\helper\Time;
use think\facade\Cache;
use think\facade\Db;
use app\common\repositories\BaseRepository;
use app\common\dao\energy\EnergyMeterDayDao;
use app\common\repositories\property\users\PropertyUsersLogRepository;

/**
 * Class EnergyMeterRepository
 *
 * @mixin EnergyMeterDayDao
 */
class EnergyMeterDayRepository extends BaseRepository
{


    public function __construct(EnergyMeterDayDao $dao)
    {
        $this->dao = $dao;
    }

    public function getPropertyList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'energyMeterInfo' => function ($query) {
                    $query->bind(['energy_name' => 'energy_name', 'energy_no' => 'energy_no']);
                }
            ])
            ->order('id', 'desc')
            ->select();
        return compact('count', 'list');
    }


    public function addInfo(array $data, int $propertyId, int $userId)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {

            $data['property_id'] = $propertyId;
            $info = $this->dao->create($data);
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'ENERGY.METER.DAY.ADD', $data);
            return $info;
        });
    }


    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'ENERGY.METER.DAY.EDIT', $data);
            return $this->dao->update($info['id'], $data);
        });
    }

    public function getDetail(int $id)
    {
        $data = $this->dao->search([])
            ->where('id', $id)
            ->with([
                'energyMeterInfo' => function ($query) {
                    $query->bind(['energy_name' => 'energy_name', 'energy_no' => 'energy_no']);
                }
            ])
            ->find();
        return $data;
    }

    public function batchDelete(array $ids, int $userId = 0)
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids]
        ]);
        if ($list) {
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId);
            }
            return $list;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0)
    {
        /** @var PropertyUsersLogRepository $repository */
        $repository = app()->make(PropertyUsersLogRepository::class);
        $repository->addInfo($info['property_id'], $userId, 'ENERGY.METER.DAY.DEL', $info);
        $this->dao->delete($info['id']);
    }

    /**
     * 获取电表操作记录  走势图
     * @param int $energyId 电表ID
     * @param array $param 搜索参数
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getEnergyMeterDayList(int $energyId, $param)
    {
        $query = $this->dao->getSearch(['energy_id' => $energyId]);
        $query->when(isset($param['time']) && $param['time'] !== '', function ($query) use ($param) {
            if ($param['time'] == 'week') {
                $query->whereBetween('add_time', Time::dayToNow(7));
            } elseif ($param['time'] == 'month') {
                $query->whereBetween('add_time', Time::month());
            } elseif ($param['time'] == 'prevMonth') {
                $query->whereBetween('add_time', Time::lastMonth());
            } else {
                $times = explode(' - ', $param['time']);
                $startTime = $times[0];
                $endTime = $times[1];
                $query->whereTime('add_time', 'between', [$startTime, $endTime]);
            }
        });
        $list = $query->order('add_time', 'asc')
            ->select()->toArray();
        return $list;
    }


    public function addData($meterInfo, $readZ = 0, $readJ = 0, $readF = 0, $readP = 0, $readG = 0, $time = '')
    {
        $time = $time ?: date('Y-m-d', time() - 86400);
        $timeDayInfo = $this->dao->search([
            'energy_id' => $meterInfo['id']
        ])->where('day_time', $time)->find();
        if ($timeDayInfo) {
            return false;
        }
        # 上次抄表记录
        $beilv = $meterInfo['beilv'] ?? 1;
        $lastDayInfo = $this->dao->getLastInfo($meterInfo['id']);
        if (!empty($lastDayInfo) && $lastDayInfo['id'] > 0) {
            ## 查昨天的 记录
            $useZ = bcmul(bcsub($readZ, $lastDayInfo['base_z'], 2), $beilv, 2);
            $useJ = bcmul(bcsub($readJ, $lastDayInfo['base_j'], 2), $beilv, 2);
            $useF = bcmul(bcsub($readF, $lastDayInfo['base_f'], 2), $beilv, 2);
            $useP = bcmul(bcsub($readP, $lastDayInfo['base_p'], 2), $beilv, 2);
            $useG = bcmul(bcsub($readG, $lastDayInfo['base_g'], 2), $beilv, 2);
        } else {
            $useZ = bcmul(bcsub($readZ, $meterInfo['read_z'], 2), $beilv, 2);
            $useJ = bcmul(bcsub($readJ, $meterInfo['read_j'], 2), $beilv, 2);
            $useF = bcmul(bcsub($readF, $meterInfo['read_f'], 2), $beilv, 2);
            $useP = bcmul(bcsub($readP, $meterInfo['read_p'], 2), $beilv, 2);
            $useG = bcmul(bcsub($readG, $meterInfo['read_g'], 2), $beilv, 2);
        }
        $data = [
            'property_id' => $meterInfo['property_id'] ?? '0',
            'property_id' => $meterInfo['property_id'] ?? '0',
            'room_id' => $meterInfo['room_id'] ?? '0',
            'energy_id' => $meterInfo['id'],
            'base_z' => $readZ,
            'base_j' => $readJ,
            'base_f' => $readF,
            'base_p' => $readP,
            'base_g' => $readG,
            'read_num_z' => $readZ,
            'read_num_j' => $readJ,
            'read_num_f' => $readF,
            'read_num_p' => $readP,
            'read_num_g' => $readG,
            'beilv' => $beilv,
            'use_num_z' => $useZ,
            'use_num_j' => $useJ,
            'use_num_f' => $useF,
            'use_num_p' => $useP,
            'use_num_g' => $useG,
            'day_time' => $time,
            'add_time' => date('Y-m-d H:i:s')
        ];
        return $this->dao->create($data);
    }

    /**
     *  用户端 每日用量查询
     * @param array $where
     * @param $page
     * @param $limit
     * @param $propertyId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-04-13 21:28
     */
    public function getApiMeterDayList(array $where, $page, $limit, $propertyId)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->order('id', 'desc')
            ->hidden(['property_id', 'property_id', 'room_id', 'add_time'])
            ->select();
        return compact('list', 'count');
    }


    /**
     * 获取设备当日缓存数据
     * @param $meterId
     * @return false|mixed
     *
     * @author Amos
     * 2024-05-18 18:17
     */
    public function getDayCacheData($energyId)
    {
        $cache = 'energy_day_' . date('Ymd') . '_' . $energyId;
        if (!Cache::has($cache)) {
            return false;
        }
        return Cache::get($cache);
    }
}